<?php

/**
 * Class Api_controller
 * 接口公用控制器
 */
class Api_controller extends BS_Controller
{

    public $user = '';

    public function __construct($check_token = false)
    {
        parent::__construct();

        // 引用常用辅助函数
        $this->load->helper('json');

        // 检查token
        if ($check_token) {
            // 参数效验
            $token = $this->input->get('token');
            if (!preg_match('/^[A-Za-z0-9+\/=]+$/i', $token)) {
                echo json_encode_ex(array('result' => 10001));
                exit;
            }

            // 拆解token
            $token = str_replace('-', '+', $token);
            $token = str_replace('_', '/', $token);
            $token_txt = base64_decode($token);
            $token_arr = explode('#', $token_txt);

            // token效验
            $this->load->model('redis_model');
            $safety = $this->redis_model->getHash('safety', $token_arr[0]);
            if (is_null($safety)) {
                // token不存在
                echo json_encode_ex(array('result' => 30002));
                exit;
            }
            if ($safety['token'] != $token) {
                // token错误
                echo json_encode_ex(array('result' => 30001));
                exit;
            }

            // token数据导入
            $this->user = (object) $safety;
        }
    }

    public function response($data)
    {
        $this->load->helper('json_helper');
        echo api_jsonp_encode($data);
        exit;
    }

}
